package ca.cbc.giscommon.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ca.cbc.giscommon.util.GISConfig;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;

public enum GeometryUtil {
	instance;
	private Logger logger = LoggerFactory.getLogger(GeometryUtil.class);
	private final int SRID;
	
	GeometryUtil() {
		SRID = Integer.parseInt(GISConfig.instance.getProperty("geometry.srid"));
	}
	
	public int getSRID() {
		return SRID;
	}
	
	/**
	 * Note, it's coordinate (x,y) passed in, not latitude and longitude
	 * @param pointCoordinate
	 * @return
	 */
	public Geometry parsePoint(String pointCoordinate) {
		if(pointCoordinate == null || !pointCoordinate.contains(",")) {
			logger.error("Cannot parse empty/incorrect coordinate {}.", pointCoordinate);
			return null;
		}
		
		String[] locationArray = pointCoordinate.split(",");
		return parsePoint(Double.parseDouble(locationArray[0].trim()), Double.parseDouble(locationArray[1].trim()));
	}
	
	public Geometry parsePoint(double x, double y) {
        Geometry geom = new GeometryFactory().createPoint(new Coordinate(x, y));
        geom.setSRID(SRID);
        
        return geom;
	}
	
    /**
     * Convert a north-east point and a south-west point to a Geometry bounding box
     * @param neStr -- (latitude, longitude)
     * @param swStr -- (latitude, longitude)
     * @return
     */
    public Geometry parseEnvelope(String neStr, String swStr) {
    	if(neStr == null || swStr == null || neStr.trim().equals("") || swStr.trim().equals("") 
    			|| !neStr.contains(",") || !swStr.contains(",")) {
    		return null;
    	}
    	
    	String[] neStrArray = neStr.split(",");
    	String[] swStrArray = swStr.split(",");
    	
    	if(neStrArray.length != 2 || swStrArray.length != 2) {
    		return null;
    	}
    	
    	Coordinate ne = new Coordinate(Double.parseDouble(neStrArray[1]), Double.parseDouble(neStrArray[0]));
    	Coordinate sw = new Coordinate(Double.parseDouble(swStrArray[1]), Double.parseDouble(swStrArray[0]));
    	Geometry geom = new GeometryFactory().toGeometry(new Envelope(ne, sw));
    	geom.setSRID(SRID);
    	return geom;
    }
}
